<template>
    <div class="all">
        <!-- <div style="text-align:center;font-size:28px;font-weight:bold;">{{$route.name}}</div> -->
        <div
            
            style="text-align:center;font-size:28px;font-weight:bold;"
        >{{$route.name}}</div>
        <el-page-header @back="goBack" :content="$route.name"></el-page-header>
        <div class="search">
            <el-form ref="form" :model="promoterSearch" :inline="true" size="mini">
                <!-- <el-form-item label="推广人：">
                    <el-input v-model="promoterSearch.name" clearable placeholder="请输入推广人"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="合作负责人：">
                    <el-input v-model="promoterSearch.principal" clearable placeholder="请输入合作负责人"></el-input>
                </el-form-item>
                <el-form-item label="负责人电话：">
                    <el-input
                        v-model="promoterSearch.principalPhone"
                        clearable
                        placeholder="请输入负责人电话"
                    ></el-input>
                </el-form-item> -->
                <el-form-item>
                    <el-select v-model="promoterSearch.state" placeholder="请选择" clearable>
                        <el-option label="未结算" value="0"></el-option>
                        <el-option label="已结算" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker
                        v-model="promoterSearch.dataTime"
                        type="daterange"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchClick">查 询</el-button>
                    <span v-if="jurisdiction.export_state === 1">
                        <el-button type="warning" @click="download">导出</el-button>
                        <a class="dn" id="exportToExcel" style="visibility:hidden"></a>
                    </span>
                    <span v-else></span>
                </el-form-item>
            </el-form>
        </div>
        <!-- <div class="btn">
            <el-button size="medium" type="primary" @click="add()">添 加</el-button>
            <el-button type="primary" @click="lookdetails">详情</el-button>
        </div> -->
        <div class="table">
            <!-- 表格 -->
            <el-table
                :data="promoterTable"
                border
                height="560"
                :style="{width:screenWidth+'px'}"
                :cell-style="cellStyle"
                :header-cell-style="rowClass"
                @selection-change="allSelectionChange"
            >
                <!-- <el-table-column type="selection" width="60px"></el-table-column> promoterSearch-->
                <el-table-column label="姓名" width="120px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="手机号" width="180px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="注册用户数" width="100px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.total_num }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="仅注册用户" width="100px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.un_add_num }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="有车用户数" width="100px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.add_num }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="日期" width="120px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.create_time*1000 | formatDate }}</span><!--  {{ scope.row.create_time*1000 | formatDateBehind }} -->
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240px">
                    <template slot-scope="scope">
                        <!-- <el-button
                            size="small"
                            type="primary"
                            @click="edit(scope.$index, scope.row)"
                        >修改</el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="remove(scope.$index, scope.row)"
                        >删除</el-button> -->
                        <div v-if="jurisdiction.update_state === 1">
                            <span v-if="scope.row.state === 1">已结算</span>
                            <el-button 
                                v-else
                                @click="refund(scope.$index,scope.row)"
                                size="small"
                                type="danger"
                            >结算</el-button>
                        </div>
                        <div v-else>
                            <span v-if="scope.row.state === 1">已结算</span>
                            <span v-else>待结算</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                @size-change="pageCount"
                @current-change="currentPageCount"
                :current-page="currentPage"
                :page-sizes="[10, 50,100,150, 200]"
                :page-size="currentCount"
                layout="prev, pager, next, jumper, sizes,total"
                :total="pageResultSize"
            ></el-pagination>
        </div>
        <div>
            <!-- 添加对话框 -->
            <!-- <el-dialog title="添加" width="60%" :visible.sync="addVisible" center @close="closeAdd">
                <el-form :model="addpromoter" ref="addpromoter" :rules="rules">
                    <el-form-item label="推广人：" prop="name" :label-width="formLabelWidth">
                        <el-input clearable v-model="addpromoter.name" placeholder="请输入推广人"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" prop="phone" :label-width="formLabelWidth">
                        <el-input clearable v-model="addpromoter.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="门店：" prop="shop_id" :label-width="formLabelWidth">
                        <el-select v-model="addpromoter.shop_id">
                            <el-option v-for="item in shopname" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="cancelAdd">取 消</el-button>
                    <el-button type="primary" @click="confirmAdd">确 定</el-button>
                </div>
            </el-dialog> -->
            <!-- 修改对话框 pickerOptions-->
            <!-- <el-dialog title="修改" width="60%" :visible.sync="editVisible" center @close="closeEdit">
                <el-form :model="editpromoter" ref="editpromoter" :rules="rules">
                    <el-form-item label="推广人：" prop="promoter" :label-width="formLabelWidth">
                        <el-input clearable v-model="editpromoter.name" placeholder="请输入推广人"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" prop="phone" :label-width="formLabelWidth">
                        <el-input clearable v-model="editpromoter.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="cancelEdit">取 消</el-button>
                    <el-button type="primary" @click="confirmEdit">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog center :visible.sync="dialogVisible" width="500px">
                <div style="text-align:center;">
                    <img width="250px" height="auto" :src="dialogImageUrl" alt />
                </div>
            </el-dialog> -->
        </div>
    </div>
</template>

<script>
import "../../../../static/scss/page.scss";
import utils from "../../../util/request";
import {formatDate } from '../../../util/time.js';
import {timetamp} from "../../../util/time.js"
import {timedata} from "../../../util/time.js"
import {date} from "../../../util/time.js"
export default {
    data() {
        return {
            // 分页
            jurisdiction: null,
            currentPage: 1, //初始页面
            currentCount: 10, //当前页面的数据数量
            pageResultSize: 10, //表格数据总数
            screenWidth: window.innerWidth, //可视宽度
            addVisible: false, //添加对话框
            editVisible: false, //修改对话框
            dialogVisible: false, //放大图片的对话框显示
            dialogImageUrl: "", //放大图片的路径
            formLabelWidth: "100px", //表单label宽度
            promoterSearch: {
                //查询框表单
                name: "", //推广人
                phone: "", //手机号
                state: "", //状态
                dataTime: ""
            },
            addpromoter: {
                //添加对话框表单
                id: "",
                name: "", //推广人
                phone: "", //手机号
                create_time: "",//创建时间
                code_url: "",//推广码地址
                shop_id: ""//门店
            },
            editpromoter: {
                //修改对话框表单
                name: "", //推广人
                phone: "" //手机号
            },
            rules:{
                name:[
                    {required:true,message:"请输入添加的推广人",trigger:"blur"}
                ],
                phone:[
                    {required:true,message:"请输入添加推广人手机号",trigger:"blur"}
                ],
                shop_id:[
                    {required:true,message:"请选择对应的店铺",trigger:"blur"}
                ]
            },
            promoterTable: [],
            shopname: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                }
            },
        };
    },
    filters:{
         // 时间
		formatDate(time){
			var date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd');
		},
		formatDateBehind(time){
			var date = new Date(time);
			return formatDate(date, 'hh:mm:ss')
		}
    },
    methods: {
        goBack: function() {
            // 页头的返回
            this.$router.go(-1);
        },
        searchClick() {
            // 查询
            let data = {page:this.currentPage,list_rows:this.currentCount}
            if(this.promoterSearch.dataTime !== "" && this.promoterSearch.dataTime !== null){  
                data.haveTime = "1";
                data.start_time = timetamp(String(this.promoterSearch.dataTime[0]));//开始时间
                data.end_time = timedata(this.promoterSearch.dataTime[1]);//结束时间))
            }
            data.state = this.promoterSearch.state
            for(var i in data) data[i] === "" ? delete data[i] : "";
            console.log(data)
            utils.request("/promoterDetails/list","post",JSON.stringify(data)).then(resp=>{
                console.log(resp)
                let data = resp.data.data;
                data.forEach((item)=>{
                    data.visible = false;
                })
                this.promoterTable = data;
                this.pageResultSize = resp.data.code;
            })
        },
        refund(index,row){
            this.$confirm('此作钱将直接转入对方绑定账户无法追回, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                utils.request("/promoterDetails/update","post",JSON.stringify({id:row.id,state:1})).then(resp=>{
                    console.log(resp)
                    this.promoterTable[index].state = 1 
                    this.$message({
                        type: 'success',
                        message: '退款成功!'
                    });
                }) 
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消退款'
                });          
            });
        },
        // add() {  1603296000  1603382400    1603161336    1603161336
        //     // 添加券码活动
        //     this.addVisible = true;
        // },

        // confirmAdd() {
        //     // 确认添加
        //     this.$refs.addpromoter.validate((valid)=>{
        //         if(valid){       
        //             let data = {}
        //             for(var i in this.addpromoter) this.addpromoter[i] !== '' ? data[i] = this.addpromoter[i] : '';

        //             let timestamp = Date.parse(new Date());
        //             data.create_time = String(timestamp/1000)
        //             data.code_url = null
        //             // console.log(data)
        //             utils.request("/promoter/add","post",JSON.stringify(data)).then(resp=>{
        //                 console.log(resp)
        //                 data.id = resp.data.data;
        //                 this.promoterTable.length < this.currentCount ? this.promoterTable.push(data) : '';
        //                 this.addVisible = false;
        //                 this.addpromoter.name = ""; //推广人
        //                 this.addpromoter.phone = ""; //手机号
        //                 this.addpromoter.shop_id = ""; //手机号
        //             })
        //         }else{this.$message.error("添加信息不能为空")}
        //     })
        // },
        // cancelAdd() {
        //     // 取消添加
        //     this.addVisible = false;
        //     this.addpromoter.promoter = ""; //推广人
        //     this.addpromoter.phone = ""; //手机号
        // },
        // closeAdd() {
        //     // 关闭添加对话框
        //     this.addVisible = false;
        //     this.addpromoter.promoter = ""; //推广人
        //     this.addpromoter.phone = ""; //手机号
        // },
        // download(index, row) {
        //     // 下载
        // },
        // edit(index, row) {
        //     // 修改的触发函数
        //     this.editVisible = true;
        //     this.editpromoter.id = row.id; //表ID
        //     this.editpromoter.name = row.name; //推广人
        //     this.editpromoter.phone = row.phone; //手机号
        //     this.editpromoter.index = index; //手机号
        //     console.log(this.editpromoter)
        // },
        // confirmEdit() {
        //     // 确认修改
        //     this.$refs.editpromoter.validate((valid)=>{
        //         if(valid){
        //             let data = {}
        //             for(var i in this.editpromoter) i !== "index" ? data[i] = this.editpromoter[i] : '';
        //             console.log(data)
        //             utils.request("/promoter/update","post",JSON.stringify(data)).then(resp=>{
        //                 console.log(resp)
        //                 let key = this.editpromoter.index;
        //                 for(var o in data) this.promoterTable[key][o] = data[o];
        //                 this.editVisible = false;
        //                 this.editpromoter.promoter = ""; //推广人
        //                 this.editpromoter.phone = ""; //手机号
        //             })       
        //         }
        //     })
        // },
        // cancelEdit() {
        //     // 取消修改
        //     this.editVisible = false;
        //     this.editpromoter.promoter = ""; //推广人
        //     this.editpromoter.phone = ""; //手机号
        // },
        // closeEdit() {
        //     // 关闭修改对话框
        //     this.editVisible = false;
        //     this.editpromoter.promoter = ""; //推广人
        //     this.editpromoter.phone = ""; //手机号
        // },
        // remove(index, row) {
        //     // 删除 二级确认
        //     this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(() => {
        //         utils.request("/promoter/delete","post",JSON.stringify({id:row.id})).then(resp=>{
        //             console.log(resp)
        //             this.promoterTable.splice(index,1) 
        //             this.$message({
        //                 type: 'success',
        //                 message: '删除成功!'
        //             });
        //         }) 
        //     }).catch(() => {
        //         this.$message({
        //             type: 'info',
        //             message: '已取消删除'
        //         });          
        //     });
            
        // },
        //   表格居中
        cellStyle: function({ row, column, rowIndex, columnIndex }) {
            return "text-align:center;";
        },
        rowClass: function({ row, rowIndex }) {
            return "text-align:center;";
        },
        allSelectionChange: function(val) {
            // 获取选中的内容
            console.log(val);
        },
        // lookUser(index, row){
        //     // 跳转用户
        //     this.$router.push({ path: "/spreadUser", query: { row: JSON.stringify(row) } });
        // },
        // lookdetails(){
        //     this.$router.push({ path: "/spreaddetails" })
        // },
        // browse(index, row) {
        //     console.log(index, row);
        //     this.dialogImageUrl = 'https://dzylab.dpyun.site'+row.code_url;
        //     this.dialogVisible = true;
        // },
        // 每页数据的数量
        pageCount: function(val) {
            this.currentCount = val;
            this.searchClick()
        },
        // 点击的第几页
        currentPageCount: function(val) {
            this.currentPage = val;
            this.searchClick()
        },
        // createimg(index,row){
        //     // console.log(row)
        //     utils.request("/qrcode/qrcode","post",JSON.stringify({id: row.id})).then(resp=>{
        //         // console.log(resp)
        //         this.promoterTable[index].code_url = resp.data.data
        //     })
        // },
        // 店铺名
        requestshops(){
            utils.request("/shop/list","post",JSON.stringify({page:1,list_rows:999999999})).then(resp=>{
                console.log(resp)
                this.shopname = resp.data.data.data.map(item=>{
                    return{
                        id: item["id"],
                        name: item["name"]
                    }
                })
            })
        },
        download(){
            let data={};// = {page:this.currentPage,list_rows:this.currentCount}
            if(this.promoterSearch.dataTime !== "" && this.promoterSearch.dataTime !== null){  
                // data.haveTime = "1";
                data.start_time = timetamp(String(this.promoterSearch.dataTime[0]));//开始时间
                data.end_time = timedata(this.promoterSearch.dataTime[1]);//结束时间))
            }
            data.state = String(this.promoterSearch.state)
            for(var i in data) data[i] === "" ? delete data[i] : "";
            console.log(data)
            utils.request("/promoterDetails/exportPD","post",JSON.stringify(data)).then(res=>{
                console.log(res,res.request.responseURL)
                // 不能用
                // 下载表单内容需要转码，不然会是跳转不能下载
                let Base64 = require('js-base64').Base64;
                // 下载数据的封装，添加完整的标签代码
                const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:x="urn:schemas-microsoft-com:office:excel" 
                xmlns="http://www.w3.org/TR/REC-html40">
                <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                <x:Name>123</x:Name>
                <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                </head><body>${res.data}</body></html>`;//${resp.data}是一个table闭合标签的数据
                // 定义下载文件的类型
                const uri = 'data:application/vnd.ms-excel;base64,';
                // window.location.href = uri + Base64.encode(template);
                document.getElementById('exportToExcel').href = uri + Base64.encode(template);
                // 补后缀
                let download = {},name;
                if(this.promoterSearch.dataTime !== "" && this.promoterSearch.dataTime !== null){
                    download.start_time = this.promoterSearch.dataTime[0].substring(this.promoterSearch.dataTime[0].length-5);//开始时间
                    download.end_time = this.promoterSearch.dataTime[1].substring(this.promoterSearch.dataTime[1].length-5);//结束时间))
                    name = '推广报表('+download.start_time+' — '+download.end_time+').xls'
                }else{
                   name = "推广报表(全部).xls"
                }
                document.getElementById('exportToExcel').download = name;
                document.getElementById('exportToExcel').click();
            })
        }
    },
    created() {
        let Base64 = require("js-base64").Base64;
        let menuarr = JSON.parse(Base64.decode(sessionStorage.getItem("menuarr")))
        for(var i=0;i<menuarr.length;i++){
            // console.log(menuarr[i].link)
            if(menuarr[i].link === this.$route.meta.JumpPath){
                this.jurisdiction = menuarr[i]
            }else{}
        }
        // console.log(this.$route)
        this.searchClick()
        // this.requestshops()
    }
};
</script>
